package com.linghui.videoplus.ipai.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;
import com.linghui.videoplus.ipai.api.json.JsonAPI;
import com.linghui.videoplus.ipai.bean.VideoBean;
import com.linghui.videoplus.ipai.media.MyVideoView;
import com.linghui.videoplus.ipai.utils.FileUtils;
import com.linghui.videoplus.ipai.utils.ImageUtils;
import com.linghui.videoplus.ipai.utils.StringUtil;

public class VideoSaveActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, OnCompletionListener {
	private ImageView playImageView, saveImageView;
	private ImageView foreImageView;
	private EditText descEditText;
	private TextView descTextView;
	
	private int screenOrient = 0;
	MyVideoView videoView;
	String url = null;
	String videoId = null;
	Bitmap bitmap = null;

	private boolean isPlay = false;
	private boolean isSave = false;
	private String desc = null;
	private int mWidth = 0;
	private int mHeight = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		setContentView(R.layout.activity_video_save);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		screenOrient = this.getIntent().getIntExtra("SCREEN_QRIENT", 0);
		url = this.getIntent().getStringExtra("URL");

		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);

		mWidth = dm.widthPixels / 3;
		mHeight = dm.heightPixels;
		if (screenOrient == 2 ||screenOrient == 4) {
			mHeight = mWidth * 4 / 3;
		} else {
			mHeight = mWidth * 3 / 4;
		}

		videoId = FileUtils.getPreName(url);

		videoView = (MyVideoView) findViewById(R.id.videoView);
		videoView.setVideoPath(url);
		videoView.requestFocus();
		videoView.setOnCompletionListener(this);

		foreImageView = (ImageView) findViewById(R.id.foreImageView);
		
		playImageView = (ImageView) this.findViewById(R.id.playImageView);
		playImageView.setOnTouchListener(this);

		saveImageView = (ImageView) findViewById(R.id.saveImageView);
		saveImageView.setOnClickListener(this);

		descEditText = (EditText) findViewById(R.id.descEditText);
		descTextView=(TextView)findViewById(R.id.descTextView);
		descEditText.addTextChangedListener(mTextWatcher);

		Thread mThread = new Thread(runnable);
		mThread.start();

	}

	@Override
	protected void onPause() {
		if (videoView.isPlaying()) {
			videoView.stopPlayback();
		}
		super.onPause();

	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		foreImageView.setVisibility(View.VISIBLE);
		playImageView.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		if (v == saveImageView) {
			if (!isSave) {
				if (checkDesc()) {
					doSaveVideo();
					isSave = true;
					showToast("视频保存成功!");
					VideoCascadeActivity.launch(this, REQUEST_CODE_SAVE_VIDEO,
							REQUEST_CODE_VIDEO_CASCADE);
				}
			} else {
				showToast("视频已成功!");
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v==playImageView){
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (isPlay) {
					videoView.pause();
				} else {
					foreImageView.setVisibility(View.GONE);
					playImageView.setVisibility(View.GONE);
					videoView.start();
				}
			}
			return true;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!isSave) {
				doBack();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void doBack() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("是否保留拍摄的视频?");
		builder.setCancelable(false);
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (checkDesc()) {
					doSaveVideo();
					isSave = true;
					showToast("视频保存成功!");
				}
			}
		});
		builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				File f = new File(url);
				if (f.exists()) {
					f.delete();
				}
				CameraActivity.launch(VideoSaveActivity.this,
						REQUEST_CODE_SAVE_VIDEO, REQUEST_CODE_CAMERA);
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	private void doSaveVideo() {
		VideoBean videoBean = new VideoBean();
		videoBean.setId(videoId);
		videoBean.setName(url.substring(url.lastIndexOf("/") + 1));
		videoBean.setImageUrl(VideoPlusApplication.imageCacheRoot + videoId
				+ ".png");
		videoBean.setVideoPath(url);
		videoBean.setCreateDate(new Date());
		videoBean.setDesc(descEditText.getText().toString());
		
		float length = (float)FileUtils.getFileSize(url);
		float mLength = length / 1024f / 1024f;
		DecimalFormat df = new DecimalFormat("0.00");
		videoBean.setSize(df.format(mLength) + "MB");
		JsonAPI jsonApi = new JsonAPI();
		jsonApi.saveMyVideo(this, videoBean);
	}

	private boolean checkDesc() {
		desc = descEditText.getText().toString();
		if (StringUtil.isEmpty(desc)) {
			showToast("请输入视频描述!");
			return false;
		}
		if (desc.length() > 60) {
			showToast("视频描述不得超过60个字!");
			return false;
		}
		return true;
	}

	public static void launch(Activity mActivity, String url, int screenOrient,
			int requestCode) {
		Intent intent = new Intent(mActivity, VideoSaveActivity.class);
		intent.putExtra("URL", url);
		intent.putExtra("SCREEN_QRIENT", screenOrient);
		intent.putExtra("REQUEST_CODE", requestCode);
		mActivity.startActivity(intent);
		mActivity.finish();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				BitmapDrawable d = new BitmapDrawable(bitmap);
				foreImageView.setBackgroundDrawable(d);
			}
		}
	};

	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			try {

				bitmap = ImageUtils.getVideoImage(url, mWidth, mHeight);
				String path = VideoPlusApplication.imageCacheRoot + videoId+ ".png";
				File dir = new File(VideoPlusApplication.imageCacheRoot);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File f = new File(path);
				if (!f.exists()) {
					f.createNewFile();
				}
				FileOutputStream out = new FileOutputStream(f);
				bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
				out.flush();
				out.close();
				mHandler.obtainMessage(1, bitmap).sendToTarget();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			String str = s.toString();
			if (str.length() > 60) {
				desc = str.substring(0, 60);
				descEditText.setText(desc);
			} else {
				desc = str;
			}
			descTextView.setText("剩余" + (60 - desc.length()) + "字");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

}
